var index;

var table;
var form;
var laydate;

$(document).ready(function () {

    $('#page-toolbar-content').show();

    layui.use(['table', 'form', 'laydate'], function () {

        table = layui.table;
        form = layui.form;
        laydate = layui.laydate;
        form.render();
        element.render();

        getAllButton(currUrl).done(function(returnData) {
            createButton(returnData);
            initButtonEvent();
            initDater();
            initTable();
            getAllDatabaseTreeData();
        });


    });

});

function initButtonEvent() {

    var $ = layui.$, active = {

        add: function () {
            chooseDatabase();
        },
        restore: function () {
            var checkStatus = table.checkStatus('database-table-content');
            var data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg("没有选取任何行！");
            }
            else if (data.length > 1) {
                layer.msg("无法批量还原！");
            }
            else {
                confirmRestore(data[0].databaseId);
            }
        },
        search: function () {

            var databaseName = $('#databaseName');
            var databaseDate = $('#databaseDate');
            var databaseType = $('#databaseType');

            // 执行重载
            table.reload('database-table-content', {
                page: {
                    curr: 1
                }
                , where: {
                    databaseName: databaseName.val(),
                    databaseDate: databaseDate.val(),
                    databaseType: databaseType.val()
                }
            });

            $('.layui-table-page').css('text-align', 'right');
            $('.layui-table-page').css('padding-right', '20px');

        }
    };

    $('.menu-btn-group .layui-btn, .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

}

function initDater() {
    laydate.render({
        elem: '#databaseDate'
    });
}

function initTable() {

    table.render({
        elem: '#database-table-content'
        , url: apiHostUrl + '/admin/database/queryDatabase'
        , headers: {Authorization: token}
        , response: {
            statusName: 'errorCode'
            , statusCode: 0
            , msgName: 'errorMsg'
            , countName: 'totalCount'
            , dataName: 'returnData'
        }
        , cellMinWidth: 50
        , limit: 15
        , limits: [15]
        , cols: [[
            {type: 'checkbox'}
            , {field: 'databaseId', width: 50, title: 'ID'}
            , {field: 'databaseName', width: 140, title: '名称'}
            , {field: 'databaseTypeString', width: 100, title: '类型'}
            , {field: 'databaseHash', title: '哈希值'}
            , {field: 'databaseDate', width: 150, title: '日期'}
            , {field: 'createUsername', width: 120,  title: '操作人'}
            , {field: 'databaseActionTime', width: 170, title: '操作时间'}
            , {field: 'toolbar', width: 170, title: '操作', align: 'center', toolbar: '#tableToolbar'}
        ]]
        , page: {
            layout: ['prev', 'page', 'next', 'skip', 'limit', 'count']
        }
        , id: 'database-table-content'
    });

    $('.layui-table-page').css('text-align', 'right');
    $('.layui-table-page').css('padding-right', '20px');

    // 监听工具条
    table.on('tool(page-table)', function (obj) {
        var data = obj.data;
        if (obj.event === 'restore') {
            confirmRestore(data.databaseId);
        }
    });

}

function getAllDatabaseTreeData() {

    // 获取当前系统数据库树
    ajax(
        "/admin/database/getDatabaseTree", "POST",
        null, true, true, false
    ).done(function (returnData) {
        createJSTree(returnData);
    });

}

function createJSTree(jsonData) {

    var tree = $('#database-tables-tree');

    tree.jstree({
        core: {
            multiple: false,
            themes: {
                responsive: !1,
            },
            data: jsonData
        },
        types: {
            default: {
                icon: "fa fa-folder icon-state-warning icon-lg"
            },
            file: {
                icon: "fa fa-file icon-state-warning icon-lg"
            }
        },
        plugins: ["types", "state"]
    });

    tree.jstree(true).settings.core.data = jsonData;
    tree.jstree(true).refresh();

}

function chooseDatabase() {

    index = layer.open({
        title: "选择要备份的库表",
        type: 1,
        id: 'layer-type-page',
        shade: 0,
        area: ['330px', '652px'],
        content:
        '<div style="text-align: center;"></div><div id="database-tree" style="padding: 20px;min-height: 500px;max-height: 500px;"></div>' +
        '<hr>' +
        '<div class="layui-form-item" style="text-align: center;margin-bottom: 5px;">' +
        '<button class="layui-btn layui-btn-default"><i class="fa fa-check fa-fw"></i>确认</button>' +
        '<button class="layui-btn layui-btn-danger"><i class="fa fa-reply fa-fw"></i>返回</button></div></div>',
        success: function(alertLayer) {
            var btn_ok = alertLayer.find('.layui-btn-default');
            btn_ok.attr({
                onclick: "javascript:confirmBackup();"
            });
            var btn_cancel = alertLayer.find('.layui-btn-danger');
            btn_cancel.attr({
                onclick: "layer.closeAll();"
            });
        }
    });

    getDatabaseTreeData();
}

function confirmBackup() {

    layer.confirm('真的要将当前数据库备份吗？', {
        btn: ['确定', '取消']
    }, function() {

        var tree = $("#database-tree");
        var nodes = tree.jstree(true).get_checked(false);

        tree.find(".jstree-undetermined").each(function (i, element) {
            nodes.push($(element).closest('.jstree-node').attr("id"));
        });

        var tableIds = nodes.map(function(data){
            return +data;
        });

        ajax(
            "/admin/database/databaseBackup", "POST",
            { databaseIds: tableIds }
            , true, true, false
        ).done(function (returnData) {
            layer.closeAll();
            loadingPage("/admin/database/database");
        });

    }, function(index) {
        layer.close(index);
    });
}

function confirmRestore(databaseId) {

    layer.confirm('真的要将当前数据库还原吗？', {
        btn: ['确定', '取消']
    }, function() {

        ajax(
            "/admin/database/databaseRestore", "POST",
            { databaseId: databaseId }
            , true, true, false
        ).done(function (returnData) {
            layer.closeAll();
            loadingPage("/admin/database/database");
        });

    }, function(index) {
        layer.close(index);
    });
}

function getDatabaseTreeData() {

    // 获取当前系统数据库树
    ajax(
        "/admin/database/getSystemDatabaseTree", "POST",
        null, true, true, false
    ).done(function (returnData) {
        createDatabaseJSTree(returnData);
    });

}

function createDatabaseJSTree(jsonData) {

    var tree = $('#database-tree');

    tree.jstree({
        core: {
            multiple: true,
            themes: {
                responsive: !1,
            },
            data: jsonData
        },
        types: {
            "default": {
                icon: "fa fa-folder icon-state-warning icon-lg"
            },
            file: {
                icon: "fa fa-file icon-state-warning icon-lg"
            }
        },
        plugins: ["types", "state", "checkbox"]
    });

    tree.jstree(true).settings.core.data = jsonData;
    tree.jstree(true).refresh();

}

